using Avalonia.Controls;
using Avalonia.Interactivity;
using IntegratedMeasuring.ViewModels.Entity;
using System;
using System.IO.Ports;
using IntegratedMeasuring.Utils;
using Avalonia.Platform.Storage;
using System.Threading.Tasks;
using Avalonia;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace IntegratedMeasuring.Pages;

public partial class SystemSettingsPage : UserControl
{
    public SystemSettingsPage()
    {
        InitializeComponent();
        Loaded += OnLoaded;
        
        // 绑定浏览按钮事件
        BrowseFilePathButton.Click += BrowseFilePathButton_Click;
        BrowseBackupPathButton.Click += BrowseBackupPathButton_Click;
        
        // 绑定扫码开关事件
        EnableBarcodeScanCheckBox.IsCheckedChanged += EnableBarcodeScanCheckBox_IsCheckedChanged;
    }

    private void OnLoaded(object? sender, RoutedEventArgs e)
    {
        LoadSettingsFromGV();
        InitializeComboBoxes();
        
        // 初始化不良重测次数的编辑状态
        bool isEnabled = !(EnableBarcodeScanCheckBox.IsChecked ?? false);
        RetestCountTextBox.IsEnabled = isEnabled;
    }

    private void InitializeComboBoxes()
    {
        // 初始化仪器型号
        InstrumentComboBox.ItemsSource = Enum.GetValues(typeof(IntegratedMeasuring.ViewModels.Entity.GC.InstrumentModelType));
        
        // 初始化串口
        var ports = SerialPort.GetPortNames();
        SerialPortComboBox.ItemsSource = ports;
        
        // 初始化波特率
        BaudRateComboBox.ItemsSource = new[] { "9600", "19200", "38400", "57600", "115200" };
        
        // 初始化主题
        ThemeComboBox.ItemsSource = new[] { "浅色主题", "深色主题", "跟随系统" };
        
        // 初始化语言
        LanguageComboBox.ItemsSource = new[] { "简体中文", "English" };
        
        // 初始化重码处理方式
        DuplicateCodeHandlingComboBox.ItemsSource = GetEnumDescriptions<IntegratedMeasuring.ViewModels.Entity.GC.DuplicateCodeHandlingType>();
    }

    private void LoadSettingsFromGV()
    {
        // 设备设置
        InstrumentComboBox.SelectedItem = GV.InstrumentModel;
        SerialPortComboBox.SelectedItem = GV.SerialPortNum;
        BaudRateComboBox.SelectedItem = GV.BaudRate.ToString();
        ServerAddressTextBox.Text = GV.ServerAddress;
        DeviceNumberTextBox.Text = GV.DeviceNumber;
        ProductionLineNumberTextBox.Text = GV.ProductionLineNumber;
        
        // 条码设置
        EnableBarcodeScanCheckBox.IsChecked = GV.EnableBarcodeScan;
        EnableBarcodeValidationCheckBox.IsChecked = GV.EnableBarcodeValidation;
        BarcodePrefixTextBox.Text = GV.BarcodePrefix;
        BarcodeSuffixTextBox.Text = GV.BarcodeSuffix;
        BarcodeLengthTextBox.Text = GV.BarcodeLength.ToString();
        RetestCountTextBox.Text = GV.RetestCount.ToString();
        DuplicateCodeHandlingComboBox.SelectedItem = GetEnumDescription(GV.DuplicateCodeHandling);
        
        // 数据设置
        FilePathTextBox.Text = GV.FilePath;
        AutoSaveIntervalTextBox.Text = GV.AutoSaveInterval.ToString();
        EnableAutoBackupCheckBox.IsChecked = GV.EnableAutoBackup;
        BackupPathTextBox.Text = GV.BackupPath;
        
        // 用户设置
        ThemeComboBox.SelectedItem = GV.Theme;
        LanguageComboBox.SelectedItem = GV.Language;
        EnableAutoLoginCheckBox.IsChecked = GV.EnableAutoLogin;
    }

    private void SaveSettingsToGV()
    {
        // 设备设置
        if (InstrumentComboBox.SelectedItem is IntegratedMeasuring.ViewModels.Entity.GC.InstrumentModelType instrumentModel)
            GV.InstrumentModel = instrumentModel;
        GV.SerialPortNum = SerialPortComboBox.SelectedItem?.ToString() ?? "";
        GV.BaudRate = int.Parse(BaudRateComboBox.SelectedItem?.ToString() ?? "9600");
        GV.ServerAddress = ServerAddressTextBox.Text;
        GV.DeviceNumber = DeviceNumberTextBox.Text;
        GV.ProductionLineNumber = ProductionLineNumberTextBox.Text;
        
        // 条码设置
        GV.EnableBarcodeScan = EnableBarcodeScanCheckBox.IsChecked ?? true;
        GV.EnableBarcodeValidation = EnableBarcodeValidationCheckBox.IsChecked ?? true;
        GV.BarcodePrefix = BarcodePrefixTextBox.Text;
        GV.BarcodeSuffix = BarcodeSuffixTextBox.Text;
        GV.BarcodeLength = int.Parse(BarcodeLengthTextBox.Text);
        GV.RetestCount = int.Parse(RetestCountTextBox.Text);
        
        // 将描述值转换回枚举值
        string selectedDescription = DuplicateCodeHandlingComboBox.SelectedItem?.ToString() ?? "另存一条";
        var enumValues = Enum.GetValues<IntegratedMeasuring.ViewModels.Entity.GC.DuplicateCodeHandlingType>();
        foreach (var enumValue in enumValues)
        {
            if (GetEnumDescription(enumValue) == selectedDescription)
            {
                GV.DuplicateCodeHandling = enumValue;
                break;
            }
        }
        
        // 数据设置
        GV.FilePath = FilePathTextBox.Text;
        GV.AutoSaveInterval = int.Parse(AutoSaveIntervalTextBox.Text);
        GV.EnableAutoBackup = EnableAutoBackupCheckBox.IsChecked ?? true;
        GV.BackupPath = BackupPathTextBox.Text;
        
        // 用户设置
        GV.Theme = ThemeComboBox.SelectedItem?.ToString() ?? "浅色主题";
        GV.Language = LanguageComboBox.SelectedItem?.ToString() ?? "简体中文";
        GV.EnableAutoLogin = EnableAutoLoginCheckBox.IsChecked ?? false;
    }

    private async void SaveSettingsButton_Click(object? sender, RoutedEventArgs e)
    {
        try
        {
            // 检查关键属性是否发生变化
            bool hasCriticalChanges = false;
            string changedItems = "";
            
            if (InstrumentComboBox.SelectedItem is ViewModels.Entity.GC.InstrumentModelType instrumentModel && instrumentModel != GV.InstrumentModel)
            {
                hasCriticalChanges = true;
                changedItems += "默认仪器、";
            }
            
            if (SerialPortComboBox.SelectedItem?.ToString() != GV.SerialPortNum)
            {
                hasCriticalChanges = true;
                changedItems += "默认串口、";
            }
            
            if (BaudRateComboBox.SelectedItem?.ToString() != GV.BaudRate.ToString())
            {
                hasCriticalChanges = true;
                changedItems += "默认波特率、";
            }
            
            if (FilePathTextBox.Text != GV.FilePath)
            {
                hasCriticalChanges = true;
                changedItems += "数据保存路径、";
            }
            
            if (hasCriticalChanges)
            {
                // 移除最后的逗号
                changedItems = changedItems.TrimEnd('、');
                
                // 显示警告信息
                NotificationHelper.ShowWarning("需要重启", 
                    $"系统设置中以下属性不能热更改，重启后生效：\n{changedItems}\n\n设置已保存，请手动重启软件。");
                
                // 保存设置但不重启
                SaveSettingsToGV();
                GV.SaveGVToLocalFile();
            }
            else
            {
                // 没有关键变化，直接保存
                SaveSettingsToGV();
                GV.SaveGVToLocalFile();
                NotificationHelper.ShowSuccess("保存成功", "系统设置已保存");
            }
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("保存失败", ex.Message);
        }
    }

    private void ResetSettingsButton_Click(object? sender, RoutedEventArgs e)
    {
        try
        {
            // 重置GV为默认值
            GV.InstrumentModel = ViewModels.Entity.GC.InstrumentModelType.TH2837AX;
            GV.SerialPortNum = "";
            GV.BaudRate = 9600;
            GV.ServerAddress = "";
            GV.DeviceNumber = "";
            GV.ProductionLineNumber = "";
            GV.EnableBarcodeScan = true;
            GV.EnableBarcodeValidation = true;
            GV.BarcodePrefix = "";
            GV.BarcodeSuffix = "";
            GV.BarcodeLength = 12;
            GV.RetestCount = 3;
            GV.DuplicateCodeHandling = IntegratedMeasuring.ViewModels.Entity.GC.DuplicateCodeHandlingType.SaveAsNew;
            GV.FilePath = "D:\\ProgramData\\IntegratedMeasuring";
            GV.AutoSaveInterval = 60;
            GV.EnableAutoBackup = true;
            GV.BackupPath = "C:\\Backup";
            GV.Theme = "浅色主题";
            GV.Language = "简体中文";
            GV.EnableAutoLogin = false;
            
            // 刷新界面
            LoadSettingsFromGV();
            NotificationHelper.ShowSuccess("重置成功", "系统设置已重置为默认值");
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("重置失败", ex.Message);
        }
    }

    private async void BrowseFilePathButton_Click(object? sender, RoutedEventArgs e)
    {
        var sp = GetStorageProvider();
        if (sp is null) return;
        
        var result = await sp.OpenFolderPickerAsync(new FolderPickerOpenOptions()
        {
            Title = "选择数据保存路径",
            AllowMultiple = false,
        });
        
        if (result.Count > 0)
        {
            FilePathTextBox.Text = result[0].Path.LocalPath;
        }
    }

    private async void BrowseBackupPathButton_Click(object? sender, RoutedEventArgs e)
    {
        var sp = GetStorageProvider();
        if (sp is null) return;
        
        var result = await sp.OpenFolderPickerAsync(new FolderPickerOpenOptions()
        {
            Title = "选择备份路径",
            AllowMultiple = false,
        });
        
        if (result.Count > 0)
        {
            BackupPathTextBox.Text = result[0].Path.LocalPath;
        }
    }

    private IStorageProvider? GetStorageProvider()
    {
        var topLevel = TopLevel.GetTopLevel(this);
        return topLevel?.StorageProvider;
    }

    private void EnableBarcodeScanCheckBox_IsCheckedChanged(object? sender, RoutedEventArgs e)
    {
        // 根据扫码开关状态控制不良重测次数的编辑状态
        bool isEnabled = !(EnableBarcodeScanCheckBox.IsChecked ?? false);
        RetestCountTextBox.IsEnabled = isEnabled;
    }
    
    // 枚举扩展方法，用于获取Description特性
    private static string GetEnumDescription(Enum value)
    {
        var field = value.GetType().GetField(value.ToString());
        var attribute = field?.GetCustomAttribute<DescriptionAttribute>();
        return attribute?.Description ?? value.ToString();
    }
    
    // 获取枚举的所有描述值
    private static string[] GetEnumDescriptions<T>() where T : Enum
    {
        return Enum.GetValues(typeof(T)).Cast<T>().Select(x => GetEnumDescription(x)).ToArray();
    }
} 